<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------


// 应用公共文件

//短信发送验证码
function hort_CodSe($Code,$phone){
    header("Content-type: text/html; charset=utf-8");
    $statusStr = array(
        "0" => "短信发送成功",
        "-1" => "参数不全",
        "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
        "30" => "密码错误",
        "40" => "账号不存在",
        "41" => "余额不足",
        "42" => "帐户已过期",
        "43" => "IP地址限制",
        "50" => "内容含有敏感词"
    );
    $smsAPI = "http://api.smsbao.com/";
    $user = "13828694229"; //短信平台帐号
    $pass = md5("138286"); //短信平台密码
    $content="【靓靓到家】您的验证码为".$Code."，在10分钟内有效。";//要发送的短信内容
    $phone = "$phone";//要发送短信的手机号码
    $sendURL = $smsAPI."sms?u=".$user."&p=".$pass."&m=".$phone."&c=".urlencode($content);
    $result =file_get_contents($sendURL) ;
    return $statusStr[$result];
}

//短信服务通知
function hort_service($address,$tel,$consignee,$phone){
    header("Content-type: text/html; charset=utf-8");
    $statusStr = array(
        "0" => "短信发送成功",
        "-1" => "参数不全",
        "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
        "30" => "密码错误",
        "40" => "账号不存在",
        "41" => "余额不足",
        "42" => "帐户已过期",
        "43" => "IP地址限制",
        "50" => "内容含有敏感词"
    );
    $smsAPI = "http://api.smsbao.com/";
    $user = "13828694229"; //短信平台帐号
    $pass = md5("138286"); //短信平台密码
    $content="【靓靓到家】地址:$address;\n联系人:$consignee;\n联系电话:$tel";//要发送的短信内容
    $phone = "$phone";//要发送短信的手机号码
    $sendURL = $smsAPI."sms?u=".$user."&p=".$pass."&m=".$phone."&c=".urlencode($content);
    $result =file_get_contents($sendURL) ;
    return $statusStr[$result];
}

function timeIff($begin_time,$end_time)
{
    if($begin_time < $end_time){
        $start_time = $begin_time;
        $end = $end_time;
    }else{
        $start_time = $end_time;
        $end = $begin_time;
    }
    //计算天数
    $time = $end-$start_time;
    $days = intval($time/86400);
    //计算小时数
    $remain = $time%86400;
    $hours = intval($remain/3600);
    //计算分钟数
    $remain = $remain%3600;
    $min = intval($remain/60);
    //计算秒数
    $secs = $remain%60;
    $time = array("day" => $days,"hour" => $hours,"min" => $min,"sec" => $secs);
    if($time["day"] >0){
        return date ("Y-m-d H:i:s",$begin_time);
    } elseif ($time["hour"] > 0){
        return $time["hour"]."小时前";
    } elseif ($time["min"] > 0){
        return $time["min"]."分钟前";
    } elseif ($time["sec"] > 0){
        return $time["sec"]."秒前";
    }
}

function API($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $res = curl_exec($ch);
    curl_close($ch);
    $obj = json_decode($res,true);
    return $obj;
}

/**
 * 产生一个随机的字符串
 */
function getCharacter($lenth)
{
    $str = '';
    $strPost = "ASDFGHJKLZXCVBNMQWERTYUIOP0123456789asdfghjklzxcvbnmqwertyuiop";
    $max = strlen($strPost) - 1;
    for($i = 0; $i < $lenth; $i++)
    {
        $str .= $strPost[rand(0, $max)];
    }
    return $str;
}

//获取当前本机的IP
function ip()
{
    if(getenv('HTTP_CLIENT_IP')){
        $onlineip = getenv('HTTP_CLIENT_IP');
    }
    elseif(getenv('HTTP_X_FORWARDED_FOR')){
        $onlineip = getenv('HTTP_X_FORWARDED_FOR');
    }
    elseif(getenv('REMOTE_ADDR')){
        $onlineip = getenv('REMOTE_ADDR');
    }
    else{
        $onlineip = $HTTP_SERVER_VARS['REMOTE_ADDR'];
    }
    return $onlineip;
}

function findImg ($id) {
    $img =action('ArticleList/findImg');
     foreach ($img as $v) {
         if ($v['id'] == $id) {
             if ($v['path']) {
                 return '__IMG__/'.$v['path'];
             }
         }
     }
    return '';
}

function result($status,$message,$data) {
    $result = array([
        'status' => $status,
        'message' => $message,
        'data' => $data
    ]);
    return $result;
}

function GetIpLookup($ip = ''){
    $res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);
    if(empty($res)){ return false; }
    $jsonMatches = array();
    preg_match('#\{.+?\}#', $res, $jsonMatches);
    if(!isset($jsonMatches[0])){ return false; }
    $json = json_decode($jsonMatches[0], true);
    if(isset($json['ret']) && $json['ret'] == 1){
        $json['ip'] = $ip;
        unset($json['ret']);
    }else{
        return false;
    }
    if($json["city"] != ""){
        return $json["city"];
    }
    if($json["province"] != ""){
        return $json["province"];
    }
    if($json["country"] != ""){
        return $json["country"];
    }
    return "汕头";
}

/**
 * 系统环境检测
 * @return array 系统环境数据
 * @author jry <598821125@qq.com>
 */
function check_env()
{
    $items = array(
        'os'     => array(
            'title'   => '操作系统',
            'limit'   => '不限制',
            'current' => PHP_OS,
            'icon'    => 'glyphicon glyphicon-ok',
        ),
        'php'    => array(
            'title'   => 'PHP版本',
            'limit'   => '5.4+',
            'current' => PHP_VERSION,
            'icon'    => 'glyphicon glyphicon-ok',
        ),
        'upload' => array(
            'title'   => '附件上传',
            'limit'   => '不限制',
            'current' => ini_get('file_uploads') ? ini_get('upload_max_filesize') : '未知',
            'icon'    => 'glyphicon glyphicon-ok',
        ),
        'gd'     => array(
            'title'   => 'GD库',
            'limit'   => '2.0+',
            'current' => '未知',
            'icon'    => 'glyphicon glyphicon-ok',
        ),
        'disk'   => array(
            'title'   => '磁盘空间',
            'limit'   => '200M+',
            'current' => '未知',
            'icon'    => 'glyphicon glyphicon-ok',
        ),
    );

    //PHP环境检测
    if ($items['php']['current'] < 5.4) {
        $items['php']['icon'] = 'glyphicon glyphicon-remove';
        session('error', true);
    }

    //GD库检测
    $tmp = function_exists('gd_info') ? gd_info() : array();
    if (!$tmp['GD Version']) {
        $items['gd']['current'] = '未安装';
        $items['gd']['icon']    = 'glyphicon glyphicon-remove';
        session('error', true);
    } else {
        $items['gd']['current'] = $tmp['GD Version'];
    }
    unset($tmp);

    //磁盘空间检测
    if (function_exists('disk_free_space')) {
        $disk_size                = floor(disk_free_space('./') / (1024 * 1024)) . 'M';
        $items['disk']['current'] = $disk_size . 'MB';
        if ($disk_size < 200) {
            $items['disk']['icon'] = 'glyphicon glyphicon-remove';
            session('error', true);
        }
    }

    return $items;
}

/**
 * 目录，文件读写检测
 * @return array 检测数据
 * @author jry <598821125@qq.com>
 */
function check_dirfile()
{
    $items = array(
        '0' => array(
            'type'  => 'dir',
            'path'  => "..".DS."runtime",
            'title' => '可写',
            'icon'  => 'glyphicon glyphicon-ok',
        ),
        '1' => array(
            'type'  => 'dir',
            'path'  => ".".DS."Uploads",
            'title' => '可写',
            'icon'  => 'glyphicon glyphicon-ok',
        ),
        '2' => array(
            'type'  => 'dir',
            'path'  => ".".DS."Data",
            'title' => '可写',
            'icon'  => 'glyphicon glyphicon-ok',
        ),
    );

    foreach ($items as &$val) {
        $path = $val['path'];
        if ('dir' === $val['type']) {
            if (!is_writable($path)) {
                if (is_dir($path)) {
                    $val['title'] = '不可写';
                    $val['icon']  = 'glyphicon glyphicon-remove';
                    session('error', true);
                } else {
                    $val['title'] = '不存在';
                    $val['icon']  = 'glyphicon glyphicon-remove';
                    session('error', true);
                }
            }
        } else {
            if (file_exists($path)) {
                if (!is_writable($path)) {
                    $val['title'] = '不可写';
                    $val['icon']  = 'glyphicon glyphicon-remove';
                    session('error', true);
                }
            } else {
                if (!is_writable(dirname($path))) {
                    $val['title'] = '不存在';
                    $val['icon']  = 'glyphicon glyphicon-remove';
                    session('error', true);
                }
            }
        }
    }
    return $items;
}

/**
 * 函数检测
 * @return array 检测数据
 */
function check_func_and_ext()
{
    $items = array(
        '0' => array(
            'type'    => 'ext',
            'name'    => 'pdo',
            'title'   => '支持',
            'current' => extension_loaded('pdo'),
            'icon'    => 'glyphicon glyphicon-ok',
        ),
        '1' => array(
            'type'    => 'ext',
            'name'    => 'pdo_mysql',
            'title'   => '支持',
            'current' => extension_loaded('pdo_mysql'),
            'icon'    => 'glyphicon glyphicon-ok',
        ),
        '2' => array(
            'type'  => 'func',
            'name'  => 'file_get_contents',
            'title' => '支持',
            'icon'  => 'glyphicon glyphicon-ok',
        ),
        '3' => array(
            'type'  => 'func',
            'name'  => 'mb_strlen',
            'title' => '支持',
            'icon'  => 'glyphicon glyphicon-ok',
        ),
    );
    foreach ($items as &$val) {
        switch ($val['type']) {
            case 'ext':
                if (!$val['current']) {
                    $val['title'] = '不支持';
                    $val['icon']  = 'glyphicon glyphicon-remove';
                    session('error', true);
                }
                break;
            case 'func':
                if (!function_exists($val['name'])) {
                    $val['title'] = '不支持';
                    $val['icon']  = 'glyphicon glyphicon-remove';
                    session('error', true);
                }
                break;
        }
    }

    return $items;
}
